package com.zhangzhan.gulimallseckill.interceptor;

import cn.hutool.core.text.AntPathMatcher;
import com.alibaba.fastjson.JSON;
import com.zhangzhan.gulimallcommcon.tos.MemberTo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Objects;

import static com.zhangzhan.gulimallcommcon.constant.AuthConstant.SESSION_USER_INFO_KEY;

/**
 * @author 张一恒
 * @version 1.0
 * @description:
 * @date 2024/6/30 11:38
 */
@Component
public class SeckillInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<MemberTo> MEMBER = new ThreadLocal<>();

    /**
     * 秒杀接口必须用户登录
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/seckill", uri);
        if (match) {
            HttpSession session = request.getSession();
            Object attribute = session.getAttribute(SESSION_USER_INFO_KEY);
            if (!Objects.isNull(attribute)) {
                MemberTo memberTo = JSON.parseObject(JSON.toJSONString(attribute), MemberTo.class);

                MEMBER.set(memberTo);
                return true;
            } else {
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }
        return true;
    }
}
